package com.sumer.juc;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;

/**
 * Set非线程安全  测试
 */
public class SetThreadTest {

    public static void main(String[] args) {
        // 底层是HashMap
//        Set<String> set = new HashSet<>(); //不安全
//        Set<String> set = Collections.synchronizedSet(new HashSet<>()); //安全
        Set<String> set = new CopyOnWriteArraySet<>(); //安全

        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString());
            }).start();
        }
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(set.size());
    }
}
